package org.example.wechat.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.wechat.mapper.UserMapper;
import org.example.wechat.config.ResponseBodyMessage;
import org.example.wechat.model.Friend;
import org.example.wechat.model.HeadPortrait;
import org.example.wechat.model.User;
import org.example.wechat.tools.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private static final String AVATAR_URL = "E:/develop/file/wechat/img/";

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestBody User u, HttpServletRequest request) {
        User user = userMapper.selectByName(u.getUsername());
        System.out.println(u.toString());
        /*
        try {
            Random random = new Random();
            int i = random.nextInt(400);
            int j = random.nextInt(400);
            int k = random.nextInt(400);
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
         */
        if (user == null) {
            return new ResponseBodyMessage<>(-1, "账户不存在", null);
        }
        if (!bCryptPasswordEncoder.matches(u.getPassword(), user.getPassword())) {
            return new ResponseBodyMessage<>(-1, "密码错误", null);
        }
        HttpSession session = request.getSession(true); // 强制创建 session
        session.setAttribute(Constant.USERINFO_SESSION_KEY, user);
        System.out.println("Session ID: " + session.getId()); // 调试输出 session ID
        return new ResponseBodyMessage<>(200, "登录成功", user);
    }

    @RequestMapping("/sign")
    //接收JSON数据格式
    public ResponseBodyMessage<Boolean> sign(@RequestBody User user) {
        System.out.println("开始注册");
        System.out.println(user.getUsername() + " : " + user.getPassword());
        User haveUser = userMapper.selectByName(user.getUsername());
        if (haveUser != null) {
            return new ResponseBodyMessage<>(-1, "账户已存在，请重新输入", false);
        }
        try {
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            System.out.println("register! user=" + user);
            int ret = userMapper.insert(user);
            System.out.println("ret: " + ret);
        } catch (org.springframework.dao.DuplicateKeyException e) {
            return new ResponseBodyMessage<>(-1, "注册失败:" + e.toString(), false);
        }
        return new ResponseBodyMessage<>(200, "注册成功", true);
    }

    @RequestMapping("/showUser")
    public ResponseBodyMessage<User> showUser(HttpSession session) {
        User user = userMapper.selectUserByUserId(1);
        System.out.println(user.toString());
        return new ResponseBodyMessage<>(200, "查看成功", user);
    }

    @RequestMapping("/selectUser")
    public ResponseBodyMessage<List<User>> selectUser(String search, String sex, String province) {
        System.out.println(search + " : " + sex);
        User user = new User();
        user.setUsername(search);
        List<User> users = userMapper.selectUserByUsername(user);
        user.setName(search);
        if (sex != null && !sex.isEmpty()) {
            user.setSex(sex);
        }
        if (province != null && !province.isEmpty()) {
            user.setProvince(province);
        }
        users.addAll(userMapper.selectUserByName(user));
        return new ResponseBodyMessage<>(200, "查询成功", users);
    }

    @RequestMapping("/insertFriend")
    public ResponseBodyMessage<Boolean> insertFriend(HttpSession session, Integer friendId) {
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        System.out.println(user.getId() + " : " + friendId);
        Friend friend = new Friend(user.getId(), friendId);
        int i = userMapper.insertFriend(friend);
        if (i == 1) {
            Friend friend1 = new Friend();
            friend1.setUserId(friend.getFriendId());
            friend1.setFriendId(friend.getUserId());
            int n = userMapper.insertFriend(friend1);
            if (n == 1) {
                return new ResponseBodyMessage<>(200, "添加成功", true);
            }
        }
        return new ResponseBodyMessage<>(-1, "添加失败", false);
    }

    @GetMapping("/getHeadPortrait")
    public ResponseEntity<byte[]> getHeadPortrait(Integer id) {
        System.out.println("传输图片");
        try {
            String imagePath = userMapper.getHeadPortraitUrlOrDefault(id);
            if (imagePath == null || imagePath.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            File imageFile = new File(AVATAR_URL + File.separator + imagePath);
            byte[] bytes = Files.readAllBytes(imageFile.toPath());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
    @RequestMapping("/insertHeadPortrait")
    public ResponseBodyMessage<Boolean> insertHeadPortrait(MultipartFile file, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //没有session不创建
        HttpSession httpSession = req.getSession(false);
        if(httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"没有登录！",false);
        }
        String filenameAndType = file.getOriginalFilename();
        System.out.println("filenameAndType--->>>>>>>>>>>>>>>>>"+filenameAndType);
        String path = AVATAR_URL +"\\"+filenameAndType;
        File dest = new File( path);
        System.out.println("dest:=>" + dest.getPath());
        if(!dest.exists()) {
            dest.mkdirs();
        }
        String title = filenameAndType.substring(0,filenameAndType.lastIndexOf("."));
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time=sf.format(new Date());
        String url = title;
        User user = (User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int ret = 0;
        try {
            ret = userMapper.insertHeadPortrait(new HeadPortrait(user.getId(),url));
        } catch (DuplicateKeyException e) {
            ret = userMapper.updateHeadPortrait(new HeadPortrait(user.getId(),url));
        }
        if(ret == 1){
        }else{
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败！",false);
        }
        return new ResponseBodyMessage<>(0,"上传成功！",true);
    }
}
